﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Net;
using SoccerScore.Compact.Linq;
using System.Linq;
using System.Data.SqlServerCe;
using HtmlAgilityPack;
using System.Data.SqlClient;
using Soccer_Score_Forecast.BulkSql;
using Soccer_Score_Forecast.BLL_CurveFit;

namespace Soccer_Score_Forecast
{
    public partial class Form1 : Form
    {
        private bool OutToMatlab(string matchtype, int rowCount)
        {
            RowNumberTable rnt = new RowNumberTable(matchtype);
            if (rnt.matchNowf.Count < rowCount || rnt.matchOverf.Count < rowCount) return false;
            dataGridView2.Columns.Clear();
            dataGridView3.Columns.Clear();
            var over = from t in rnt.matchOverf
                       select new
                       {
                           t.Analysis_result_id,
                           t.match_time,
                           t.match_type,
                           t.home_team,
                           t.away_team,
                           t.Odds,
                           t.Dodds,
                           t.Home_w,
                           t.Home_d,
                           t.Home_l,


                           t.Recent_scores,
                           t.Recent_2scores,
                           t.Recent_3scores,
                           t.Recent_4scores,
                           t.Recent_5scores,
                           t.Recent_6scores,

                           t.Home_goals,
                           t.Away_goals,
                           t.Cross_goals,
                           t.Fit_win_loss,

                           t.Full_total_goals,
                           t.Full_diff_goals,
                           t.Full_home_goals,
                           t.Full_away_goals,
                           t.Lottery_Ticket,

                       };
            var now = from t in rnt.matchNowf
                      select new
                      {
                          t.Analysis_result_id,
                          t.match_time,
                          t.match_type,
                          t.home_team,
                          t.away_team,
                          t.status,
                          t.Dodds,
                          t.Home_w,
                          t.Home_d,
                          t.Home_l,


                          t.Recent_scores,
                          t.Recent_2scores,
                          t.Recent_3scores,
                          t.Recent_4scores,
                          t.Recent_5scores,
                          t.Recent_6scores,

                          t.Home_goals,
                          t.Away_goals,
                          t.Cross_goals,
                          t.Fit_win_loss,

                      };

            var overfilter = over.OrderByDescending(e => e.Analysis_result_id).Take(1000);

            dataGridView2.DataSource = overfilter.OrderBy(e => e.Analysis_result_id).ToList();
            dataGridView3.DataSource = now.OrderBy(e => e.Analysis_result_id).ToList();
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportToExcel.ExportForDataGridview(dataGridView3, "MyGRNN", true);
        }

        private void btnSimGRNN_Click(object sender, EventArgs eee)
        {
            SimulinkGRNN();
        }

        int simulinkno = 0;
        private void SimulinkGRNN()
        {
            simulinkno++;
            bool lessDimention = false;
            richTextBox3.Text = string.Empty;
            ExportToExcel.DataGridView2Txt(dataGridView2, nn.tempy, 7);
            ExportToExcel.DataGridView2Txt(dataGridView3, nn.tempx, 7);
            StreamReader streamx = new StreamReader(nn.tempx, System.Text.Encoding.Default);
            StreamReader streamy = new StreamReader(nn.tempy, System.Text.Encoding.Default);
            SimulinkRbfLog srlog = new SimulinkRbfLog();
            SimulinkRbf simulinkrbf = new SimulinkRbf();
            try
            {
                //MessageBox.Show("ok");
                //exe文件方式
                //result = ExportToExcel.SimulinkNN(@"D:\My Documents\MATLAB\mygrnn.exe");
                //dll文件方式
                #region MyRegion  //测试程序
                srlog._id = simulinkno;
                srlog.matchtype = label9.Text;
                srlog.matchover = streamy.ReadToEnd();   //y是训练用
                srlog.matchnow = streamx.ReadToEnd();  //x是预测目标
                if (srlog.matchnow.Length < 10 || srlog.matchover.Length < 10) lessDimention = true;
                if (lessDimention)
                {
                    simulinkrbf.mongocrud.MongoCol.Insert(srlog);
                    return;
                }
                srlog.grnn = nn.NewGrnn();
                srlog.pnn = nn.NewPnn();
                simulinkrbf.mongocrud.MongoCol.Insert(srlog);
                var result = mergeGrnnPnn(srlog.grnn, srlog.pnn);
                #endregion

                //dataGridView3.Columns.Add("...", "...");
                dataGridView3.Columns.Add("MyGRNN", "MyGRNN");

                int colx = dataGridView3.Columns.Count - 1;
                int ix = 0;
                //string[] lines = result.Split(new char[] { '\r', '\n' });
                foreach (string line in result)
                //if (line != null)
                //    if (line.Trim().Length > 0)
                //        if (line.IndexOf("=") == -1)
                //        {
                {
                    richTextBox3.Text += line + "\r\n";
                    dataGridView3.Rows[ix].Cells[colx].Value = line;
                    ix++;

                }
                //}


                using (DataClassesMatchDataContext matches = new DataClassesMatchDataContext(Conn.conn))
                {
                    int resultid = 0;
                    int col = dataGridView3.Columns.Count - 1;
                    string grnnfit = null;
                    for (int i = 0; i < dataGridView3.Rows.Count; i++)
                    {
                        resultid = Int32.Parse(dataGridView3.Rows[i].Cells[0].Value.ToString());
                        grnnfit = dataGridView3.Rows[i].Cells[col].Value.ToString();
                        var mar = matches.Match_analysis_result
                            .Where(e => e.Analysis_result_id == resultid).First();//查找需要更新的数据
                        mar.Grnn_fit = grnnfit.Trim();
                    }
                    matches.SubmitChanges();
                }
                //MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                streamx.Close(); streamx.Dispose();
                streamy.Close(); streamy.Dispose();
            }
        }

        private IEnumerable<string> mergeGrnnPnn(string grnn, string pnn)
        {
            int i = -1;
            string[] linesg = grnn.Split(new char[] { '\r', '\n' });
            string[] linesp = pnn.Split(new char[] { '\r', '\n' });
            foreach (string line in linesg)
            {
                i++;
                yield return line.Trim() + ' ' + linesp[i].Trim();
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            ExportToExcel.ExportForDataGridview(dataGridView6, "CrossDetail", true);
            ExportToExcel.ExportForDataGridview(dataGridView7, "HomeTeam", true);
            ExportToExcel.ExportForDataGridview(dataGridView8, "AwayTeam", true);
        }

        NNPredication nn = new NNPredication();
        private void btnSimPNN_Click(object sender, EventArgs eee)
        {
            SimulinkPNN();
        }
        private void SimulinkPNN()
        {
            /*
            try
            {
                if (lessDimention) return;

                string result = null;
                //ExportToExcel.DataGridView2Txt(dataGridView2, @"D:\My Documents\MATLAB\yn.txt", 5);
                //ExportToExcel.DataGridView2Txt(dataGridView3, @"D:\My Documents\MATLAB\xite.txt", 6);

                //exe文件方式
                //result = ExportToExcel.SimulinkNN(@"D:\My Documents\MATLAB\mypnn.exe");

                //dll文件方式
                result = nn.NewPnn();

                richTextBox3.Text = result;

                //dataGridView3.Columns.Add("...", "...");
                dataGridView3.Columns.Add("MyPNN", "MyPNN");

                int colx = dataGridView3.Columns.Count - 1;
                int ix = 0;
                string[] lines = result.Split(new char[] { '\r', '\n' });
                foreach (string line in lines)
                //if (line != null)
                //    if (line.Trim().Length > 0)
                //        if (line.IndexOf("=") == -1)
                //        {
                {
                    dataGridView3.Rows[ix].Cells[colx].Value = line;
                    ix++;
                }
                //}


                using (DataClassesMatchDataContext matches = new DataClassesMatchDataContext(Conn.conn))
                {
                    int resultid = 0;
                    int col = dataGridView3.Columns.Count - 1;
                    string pnnfit = null;
                    for (int i = 0; i < dataGridView3.Rows.Count; i++)
                    {
                        resultid = Int32.Parse(dataGridView3.Rows[i].Cells[0].Value.ToString());
                        pnnfit = dataGridView3.Rows[i].Cells[col].Value.ToString();
                        var mar = matches.Match_analysis_result
                            .Where(e => e.Analysis_result_id == resultid).First();//查找需要更新的数据
                        mar.Pnn_fit = pnnfit.Trim();
                    }
                    matches.SubmitChanges();
                }
                //MessageBox.Show("OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
             * */
        }

        private void btnSimWNN_Click(object sender, EventArgs e)
        {
            try
            {
                string result = null;
                //总是出现问题
                //result = nn.NewffWavelet();
                //richTextBox3.Text = result;

                //用exe的方式看看
                result = ExportToExcel.SimulinkNN(@"D:\My Documents\MATLAB\mywavelet.exe");
                richTextBox3.Text = result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    }
}
